function hfile = vmp_ConvertToNatRes(hfile, res)
% VMP::ConvertToNatRes  - convert to native resolution map
%
% FORMAT:       [vmp] = vmp.ConvertToNatRes([res]);
%
% Input fields:
%
%       res         resolution, if not given, try first 3 then 2
%
% Note: the changes are in-place, so, no new object is being created

% Version:  v0.7b
% Build:    7083022
% Date:     Aug-30 2007, 10:47 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'vmp')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to ''%s''.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);
if bc.NativeResolutionFile
    return;
end

% guess resolution
bbox = aft_BoundingBox(hfile);
osz = diff(bbox.BBox) + 1;
if nargin < 2 || ...
    numel(res) ~= 1 || ...
   ~isnumeric(res) || ...
   ~any((2:12) == res)

    % test 3
    if all(mod(osz, 3) == 0)
        res = 3;
    else
        res = 2;
    end
end
if any(mod(osz, res) > 0)
    error( ...
        'BVQXfile:BadArgument', ...
        'VMP cannot be resampled, irregular grid size.' ...
    );
end

% make changes
ofv = bc.FileVersion;
bc.Resolution = res;
bc.NativeResolutionFile = 1;
bc.FileVersion = 5;
bvqxfile_setcont(hfile.L, bc);
vmp_Update(hfile, 'FileVersion', struct('type', '.', 'subs', 'FileVersion'), ofv);
